package message

import (
	"fmt"
	"strconv"
	"strings"
)

type MouseMessage struct {
	Fields    []byte
	Kind      uint8
	X         int16
	Y         int16
	Button    uint16
	Action    uint16
	Code      uint16
	Direction uint8
	Rotation  int32
	Clicks    uint16
}

func (mm *MouseMessage) Serialize() []byte {
	fields := fmt.Sprintf(
		"%d %d %d %d %d %d %d %d %d",
		mm.Kind, mm.X, mm.Y, mm.Button, mm.Action, mm.Code, mm.Direction, mm.Rotation, mm.Clicks)
	return []byte(fields)
}

func (mm *MouseMessage) UnSerialize() *MouseMessage {
	fields := strings.Fields(string(mm.Fields))
	kind, _ := strconv.Atoi(fields[0])
	mm.Kind = uint8(kind)
	x, _ := strconv.Atoi(fields[1])
	mm.X = int16(x)
	y, _ := strconv.Atoi(fields[2])
	mm.Y = int16(y)
	button, _ := strconv.Atoi(fields[3])
	mm.Button = uint16(button)
	action, _ := strconv.Atoi(fields[4])
	mm.Action = uint16(action)
	code, _ := strconv.Atoi(fields[5])
	mm.Code = uint16(code)
	direction, _ := strconv.Atoi(fields[6])
	mm.Direction = uint8(direction)
	rotation, _ := strconv.Atoi(fields[7])
	mm.Rotation = int32(rotation)
	clicks, _ := strconv.Atoi(fields[8])
	mm.Clicks = uint16(clicks)

	return mm
}

func NewMessageFromFields(fields []byte) *MouseMessage {
	m := &MouseMessage{
		Fields: fields,
	}
	m.UnSerialize()
	return m
}
